package nio.example.study.server.handler;

import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import lombok.extern.slf4j.Slf4j;
import nio.example.study.common.Operation;
import nio.example.study.common.OperationResult;
import nio.example.study.common.RequestMessage;
import nio.example.study.common.ResponseMessage;

@Slf4j
public class OrderServerProcessHandler extends SimpleChannelInboundHandler<RequestMessage> {
	@Override
	protected void channelRead0(ChannelHandlerContext ctx, RequestMessage requestMessage) throws Exception {

		Operation operation = requestMessage.getMessageBody();
		OperationResult operationResult = operation.execute();

		ResponseMessage responseMessage = new ResponseMessage();
		responseMessage.setMessageHeader(requestMessage.getMessageHeader());
		responseMessage.setMessageBody(operationResult);
		// 判断channel是否可写，防止netty OOM
		if (ctx.channel().isActive() && ctx.channel().isWritable()) {
			ctx.writeAndFlush(responseMessage);
		} else {
			log.error("message dropped");
		}

		//ctx.channel().writeAndFlush(responseMessage);
	}
}
